<?php
class calender extends base{

  function __construct()
  {
    parent::__construct();
    $this->m = load('m/calender');
    $this->submenu =  array(
      'index'=>'我的日程',
      'ref' => '我关注的'
    );
  }

  function index()
  {
    //$tot = $this->m->count();
    $psize = 300;
    //$param['pagination'] = pagination($tot , seg(3) , $psize ,'/calender/index/');
    $monthnow=isset($_GET['mon'])?$_GET['mon']:date("n");
    $yearnow=isset($_GET['year'])?$_GET['year']:date("Y");
    if($monthnow==13){
      $monthnow=1;
      $yearnow=$yearnow+1;
    }
    if($monthnow==0){
      $monthnow=12;
      $yearnow=$yearnow-1;
    }
     
    $mdays=date("t");    //当月总天数
    $datenow=date("j");  //当日日期
    // $datenow=date("j");
    //计算当月第一天是星期几
    $wk1st=date("w",mktime(0,0,0,$monthnow,1,$yearnow));
    $trnum=ceil(($mdays+$wk1st)/7); //计算表格行数
    $param = array(
      'trnum'=>$trnum,
      'wk1st'=>$wk1st,
      'mdays'=>$mdays,
      'datenow'=>$datenow,
      'monthnow'=>$monthnow,
      'yearnow'=>$yearnow,
      'now' => date('Y-m-d')
    );
    
    $rs = $this->m->get("", seg(3), $psize);
    foreach($rs as $r)
    {
      $key = $r['date'];
      $nr[$key] = $r['task'];
    }
    $param['task'] = $nr;
    $this->display('calender/home',$param);
  }

  function view($id)
  {
    $param['r'] = $this->m->get($id);
    $this->display('calender/show',$param);
  }

  function add()
  {
    $conf = array('uid'=>'required','uname'=>'required','date'=>'required','task'=>'required',);
    
    $err = validate($conf);
    if ( $err === TRUE) {
      $this->m->add();
      redirect('/calender/add','发布成功！');
    }
    else {
      $param['val'] = $_POST; 
      $param['err'] = $err;
      $this->display('calender/add',$param);    
    }
  }    

  function edit($date)
  {
    $conf = array('task'=>'required');
    $err = validate($conf);
  	if ( $err === TRUE) {
      if($_POST['id']) {
        $this->m->update($_POST['id']);
      }
      else {
        $_POST['uid'] = $this->uid;
        $_POST['uname'] = $this->uname;
        $this->m->add();
      }
      redirect('/calender','修改成功！');
    }
    else {
      $param['val'] = array_merge($_POST,$this->m->get_by_date($this->uid,$date),array('date'=>$date));
      $param['err'] = $err;
      $this->display('calender/add',$param);    
    }
  }

  function del($id)
  {
    $this->m->del($id);
    redirect('/calender/','删除成功！');
  }
}
